package com.javafactroy.kunlong.bip.icp.message.test.base;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.javafactroy.kunlong.bip.icp.common.consts.IConfig;
import io.netty.buffer.*;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import com.javafactroy.kunlong.bip.icp.common.consts.IMsgType;
import com.javafactroy.kunlong.bip.icp.message.base.base.Message;
import com.javafactroy.kunlong.bip.icp.message.base.iface.IMessage;

import java.nio.ByteBuffer;

@Data
@ToString()
@Slf4j
public class TMsg extends Message implements IMessage {

    IConfig.INettyConst.MSG_State msgState;

    int totalLen;

    TMsgHeader header;
    TMsgBody body;

    public TMsg() {
        this.header = new TMsgHeader();
        this.body = new TMsgBody();

    }


    @Override
    public byte[] encode() {
        ByteBuf byteBuf = encode2ByteBuf();
        int len = byteBuf.readableBytes();
        byte[] bytes = new byte[len];
        byteBuf.readBytes(bytes);
        byteBuf.release();
        return bytes;
    }

    public ByteBuf encode2ByteBuf() {
        ByteBuf byteBufBody = body.encode2ByteBuf();
        totalLen = TMsgHeader.msgHeaderLen + byteBufBody.readableBytes();
        header.setMessageLen(totalLen);
        ByteBuf byteBufHeader = header.encode2ByteBuf();

        log.info("encode totalLen ={}", totalLen);

        ByteBuf byteBuf =  Unpooled.wrappedBuffer(byteBufHeader, byteBufBody);
        log.info("encode2ByteBuf={}",ByteBufUtil.prettyHexDump(byteBuf));
        return  byteBuf;

    }

    @Override
    public void decode(byte[] buf) {
        if (buf.length >= TMsgHeader.msgHeaderLen) {
            header.decode(buf);
            if (buf.length >= header.getMessageLen()) {
                ByteBuffer bf = ByteBuffer.wrap(buf);
                int bodyLen = header.getMessageLen() - TMsgHeader.msgHeaderLen;
                byte[] bodys = new byte[bodyLen];
                bf.position(TMsgHeader.msgHeaderLen);
                bf.get(bodys);
                body.decode(bodys);
            }

        }
    }

    public void decode(ByteBuffer buf) {
        buf.rewind();
        decode(buf.array());

    }


    @Override
    public void check() {

    }

    @Override
    public String getMessageId() {
        return getHeader().getMessageId();
    }

    @Override
    public String getMsgType() {
        return "" + getHeader().getMessageType();
    }


    public static TMsg buildTMsg() {
        TMsg msg = buildMessage();
        msg.getHeader().setMessageType(IMsgType.MsgType_Dxp_Stub_Default);
        return msg;
    }

    public static TMsg buildMessage() {

        TMsg msg = new TMsg();

        return msg;
    }

    public static TMsg buildCloseMsg() {
        return buildMessage();
    }

    public String toJSONString() {
        return JSON.toJSONString(this, SerializerFeature.PrettyFormat);
    }


}
